package com.mufeng.gallery.flutter_gallery_saver

import android.content.Context
import android.graphics.BitmapFactory
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** FlutterGallerySaverPlugin */
class FlutterGallerySaverPlugin: FlutterPlugin, MethodCallHandler {

  private lateinit var channel : MethodChannel
  private lateinit var context: Context

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    context = flutterPluginBinding.applicationContext
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flutter_gallery_saver")
    channel.setMethodCallHandler(this)
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    when {
      call.method == "saveImageToGallery" -> {
        val image = call.argument<ByteArray>("imageBytes") ?: return
        val quality = call.argument<Int>("quality") ?: return
        val name = call.argument<String>("name")
        GalleryUtils.saveImageToGallery(context,BitmapFactory.decodeByteArray(image,0,image.size), quality, name, result)
      }
      call.method == "saveImageToGalleryForUrl" -> {
        val path = call.argument<String>("file") ?: return
        GalleryUtils.saveImageToGalleryWithUrl(context,path,result)
      }
      call.method == "saveVideoToGallery" -> {
        val path = call.argument<String>("file") ?: return
        GalleryUtils.saveVideoToGallery(context, path, result)
      }
      else -> result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }
}
class SaveResultModel (var isSuccess: Boolean,
                       var filePath: String? = null,
                       var errorMessage: String? = null) {
  fun toHashMap(): HashMap<String, Any?> {
    val hashMap = HashMap<String, Any?>()
    hashMap["isSuccess"] = isSuccess
    hashMap["filePath"] = filePath
    hashMap["errorMessage"] = errorMessage
    return hashMap
  }
}